package com.hyg.module_report.ui.fragment;

import android.content.Context;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.hyg.lib_common.DataModel.ReceiveData;
import com.hyg.lib_common.DataModel.report.DietHealthData;
import com.hyg.lib_common.DataModel.report.IntroductionData;
import com.hyg.lib_common.DataModel.report.MedicatedBathData;
import com.hyg.lib_common.DataModel.report.MotionCareData;
import com.hyg.lib_common.DataModel.report.MoxibustionData;
import com.hyg.lib_common.DataModel.report.SeasonHealthData;
import com.hyg.lib_common.DataModel.report.TeaHealthData;
import com.hyg.lib_common.DataUtil.UserSPUtils;
import com.hyg.lib_common.constant.UrlUtils;
import com.hyg.lib_common.constant.FileConstants;
import com.hyg.module_report.R;
import com.hyg.module_report.adapter.HealthAdviceAdapter;
import com.hyg.module_report.model.HealthCareData;
import com.hyg.module_report.model.ReportIDToHealthCareID;
import com.hyg.module_report.model.V2AdviceDetailData;
import com.hyg.module_report.ui.activity.HealthReportActivity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;

/**
 * create an instance of this fragment.
 */
public class HealthAdviceDetailFragment extends Fragment {
    HealthReportActivity Activity;
    private RecyclerView RV_advice_detail;
    private HealthAdviceAdapter healthAdviceAdapter;
    private ArrayList<HealthCareData> HealthCareData_dataList = new ArrayList<HealthCareData>();
    private ArrayList<HealthCareData> HealthCareData_xiezi = new ArrayList<HealthCareData>();
    private ArrayList<HealthCareData> HealthCareData_yundong = new ArrayList<HealthCareData>();
    //    private ArrayList<SpannableString> HealthCareData_yundongjinji = new ArrayList<SpannableString>();
    private ArrayList<HealthCareData> HealthCareData_yingji = new ArrayList<HealthCareData>();
    private ArrayList<HealthCareData> HealthCareData_shanshi = new ArrayList<HealthCareData>();
    private ArrayList<HealthCareData> HealthCareData_yaoyu = new ArrayList<HealthCareData>();
    private ArrayList<HealthCareData> HealthCareData_aijiu = new ArrayList<HealthCareData>();
    private ArrayList<HealthCareData> HealthCareData_chayin = new ArrayList<HealthCareData>();

    private ReportIDToHealthCareID reportIDToHealthCareID = new ReportIDToHealthCareID();
    private ArrayList<String> xiezi = new ArrayList<>();
    private ArrayList<String> yundong = new ArrayList<>();
    private ArrayList<String> yingji = new ArrayList<>();
    private ArrayList<String> shanshi = new ArrayList<>();
    private ArrayList<String> yaoyu = new ArrayList<>();
    private ArrayList<String> aijiu = new ArrayList<>();
    private ArrayList<String> chayin = new ArrayList<>();

    public HealthAdviceDetailFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        Activity = (HealthReportActivity) getActivity();
        UserSPUtils.clearHealthAdviceInfo(Activity);
        init_advice_detail();
        getReportDetailData();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_health_advice_detail, container, false);
        RV_advice_detail = view.findViewById(R.id.RV_advice_detail);
        return view;
    }

    /**
     * description: 查询报告和建议 详细信息
     *
     * @author visitant
     * @time 2020/12/10 10:19
     */
    public void getReportDetailData() {
        getXieZieInfo(Activity.MedicalId);
        getSeasonInfo(Activity.MedicalId);
        getSportsInfo(Activity.MedicalId);
        getDietInfo(Activity.MedicalId);
        getMethodAddrInfo(Activity.MedicalId);
        getTeaInfo(Activity.MedicalId);
        getMoxibustionAddrInfo(Activity.MedicalId);
    }

    public void getreportList(String id) {
        Log.d("welcomereportListDetail", Activity.sn.getString("token", "") + " -- " + id);
        String str_tag = "1";
        FormBody formBody = new FormBody.Builder()
                .add("token", Activity.sn.getString("token", ""))//设置参数名称和参数值
                .add("reportId", id)
                .build();
        Activity.sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.reportListAddr);
    }

    public void storageReportList() {
        /*  将养生建议直接存入sp,回到首页直接刷新，不退出   */
        Gson gson = new Gson();
        String jsonStr = gson.toJson(reportIDToHealthCareID); //将List转换成Json
        Activity.editorn = Activity.sn.edit();
        Activity.editorn.putString("ReportIDToHealthCareID", jsonStr); //存入json串
        Activity.editorn.commit();  //提交
    }

    public void getMoxibustionAddrInfo(String id) {
        String str_tag = "17";
        FormBody formBody = new FormBody.Builder()
                .add("reportId", id)//设置参数名称和参数值
                .add("token", Activity.sn.getString("token", ""))//设置参数名称和参数值
                .build();
        Activity.sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getMoxibustionAddr);
    }

    public void getTeaInfo(String id) {
        String str_tag = "16";
        FormBody formBody = new FormBody.Builder()
                .add("reportId", id)//设置参数名称和参数值
                .add("token", Activity.sn.getString("token", ""))//设置参数名称和参数值
                .build();
        Activity.sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getTeaAddr);
    }

    public void getMethodAddrInfo(String id) {
        String str_tag = "15";
        FormBody formBody = new FormBody.Builder()
                .add("reportId", id)//设置参数名称和参数值
                .add("token", Activity.sn.getString("token", ""))//设置参数名称和参数值
                .build();
        Activity.sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getMethodAddr);
    }

    public void getDietInfo(String id) {
        String str_tag = "14";
        FormBody formBody = new FormBody.Builder()
                .add("reportId", id)//设置参数名称和参数值
                .add("token", Activity.sn.getString("token", ""))//设置参数名称和参数值
                .build();
        Activity.sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getDietAddr);
    }

    public void getSeasonInfo(String id) {
        String str_tag = "13";
        FormBody formBody = new FormBody.Builder()
                .add("reportId", id)//设置参数名称和参数值
                .add("token", Activity.sn.getString("token", ""))//设置参数名称和参数值
                .build();
        Activity.sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getSeasonAddr);
    }

    public void getSportsInfo(String id) {
        String str_tag = "12";
        FormBody formBody = new FormBody.Builder()
                .add("reportId", id)//设置参数名称和参数值
                .add("token", Activity.sn.getString("token", ""))//设置参数名称和参数值
                .build();
        Activity.sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getSportsAddr);
    }

    public void getXieZieInfo(String id) {
        String str_tag = "11";
        FormBody formBody = new FormBody.Builder()
                .add("reportId", id)//设置参数名称和参数值
                .add("token", Activity.sn.getString("token", ""))//设置参数名称和参数值
                .build();
        Activity.sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.getXieZiAddr);
    }

    public void setRV_advice_detail() {
        HealthCareData_dataList.clear();
        HealthCareData_dataList.addAll(HealthCareData_xiezi);
        HealthCareData_dataList.addAll(HealthCareData_yundong);
        HealthCareData_dataList.addAll(HealthCareData_yingji);
        HealthCareData_dataList.addAll(HealthCareData_shanshi);
        HealthCareData_dataList.addAll(HealthCareData_yaoyu);
        HealthCareData_dataList.addAll(HealthCareData_aijiu);
        HealthCareData_dataList.addAll(HealthCareData_chayin);
        healthAdviceAdapter.notifyDataSetChanged();
    }

    /**
     * description:养生建议
     *
     * @author visitant
     * @time 2020/12/10 9:57
     */
    public void init_advice_detail() {
        healthAdviceAdapter = new HealthAdviceAdapter(getActivity(), HealthCareData_dataList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        RV_advice_detail.setLayoutManager(layoutManager);
        RV_advice_detail.setItemAnimator(new DefaultItemAnimator());
        RV_advice_detail.setAdapter(healthAdviceAdapter);
    }


    /**
     * description: 显示楔子养生信息
     *
     * @author visitant
     * @time 2020/12/11 17:25
     */
    public void showXieziHealthData(String msg) {
        ReceiveData receiveData = JSONObject.parseObject(msg, ReceiveData.class);
        if (!receiveData.getCode().equals("200")) {
            Activity.ErrorDialog(receiveData.getMessage());
        } else {
            List<IntroductionData> introductionData = JSONArray.parseArray(receiveData.getData(), IntroductionData.class);
            HealthCareData_xiezi.clear();
            xiezi.clear();
            for (int i = 0; i < introductionData.size(); i++) {
                HealthCareData AdDatas = new HealthCareData(introductionData.get(i).getId() + "",
                        "",
                        "楔子养生",
                        introductionData.get(i).getIntroductionImages(),
                        introductionData.get(i).getIntroductionContent());
                HealthCareData_xiezi.add(AdDatas);
                xiezi.add(introductionData.get(i).getId() + "");
                reportIDToHealthCareID.setXiezi(xiezi);
            }
            JSONArray array= JSONArray.parseArray(JSON.toJSONString(HealthCareData_xiezi));
            UserSPUtils.putUserString(getActivity(), FileConstants.XieZi,JSON.toJSONString(array));
            UserSPUtils.putUserString(getActivity(), FileConstants.HasReport,"true");
            setRV_advice_detail();
        }
    }


    public void showYundongData(String msg) {
        ReceiveData receiveData = JSONObject.parseObject(msg, ReceiveData.class);
        if (!receiveData.getCode().equals("200")) {
            Activity.ErrorDialog(receiveData.getMessage());
        } else {
            List<MotionCareData> motionCareDataList = JSONArray.parseArray(receiveData.getData(), MotionCareData.class);
            List<V2AdviceDetailData> yundongData = new ArrayList<>();
            HealthCareData_yundong.clear();
            yundong.clear();
            for (int i = 0; i < motionCareDataList.size(); i++) {
                String[] content = motionCareDataList.get(i).getSpcontent().split("\\r\\n");
                if (content.length > 2 && motionCareDataList.get(i).getSptag() == 0) {
                    HealthCareData AdDatas = new HealthCareData(motionCareDataList.get(i).getId() + "",
                            motionCareDataList.get(i).getSpname(),
                            "运动养生",
                            motionCareDataList.get(i).getSpimages(),
                            motionCareDataList.get(i).getRemarks(),
                            content[0], content[1], content[2]);
                    HealthCareData_yundong.add(AdDatas);
                    yundong.add(motionCareDataList.get(i).getId() + "");
                    reportIDToHealthCareID.setYundong(yundong);

                    V2AdviceDetailData V2Data=new V2AdviceDetailData();
                    V2Data.setImageUrl(motionCareDataList.get(i).getSpimages());
                    V2Data.setYsName(motionCareDataList.get(i).getSpname());
                    V2Data.setId(motionCareDataList.get(i).getId());
                    V2Data.setCategoryName("运动指导");
//                    V2Data.setBeCareful(motionCareDataList.get(i).getRemarks());
                    V2Data.setPrinciple(content[0]);
                    V2Data.setEffect(content[1]);
                    V2Data.setBeCareful(content[2]);
                    yundongData.add(V2Data);

                }
            }
            JSONArray array= JSONArray.parseArray(JSON.toJSONString(yundongData));
            UserSPUtils.putUserString(getActivity(), FileConstants.YunDong_data,JSON.toJSONString(array));
            UserSPUtils.putUserString(getActivity(), FileConstants.HasReport,"true");
            setRV_advice_detail();
        }
    }

    public void showJijieData(String msg) {
        ReceiveData receiveData = JSONObject.parseObject(msg, ReceiveData.class);
        if (!receiveData.getCode().equals("200")) {
            Activity.ErrorDialog(receiveData.getMessage());
        } else {
            List<SeasonHealthData> data = JSONArray.parseArray(receiveData.getData(), SeasonHealthData.class);
            HealthCareData_yingji.clear();
            yingji.clear();
            for (int i = 0; i < 1; i++) {
                HealthCareData AdDatas = new HealthCareData(data.get(i).getId() + "",
                        "",
                        "应季养生",
                        data.get(i).getSeasonImages(),
                        data.get(i).getSeasonContent());
                HealthCareData_yingji.add(AdDatas);
                yingji.add(data.get(i).getId() + "");
                reportIDToHealthCareID.setYingji(yingji);




            }

            JSONArray array= JSONArray.parseArray(JSON.toJSONString(HealthCareData_yingji));
            UserSPUtils.putUserString(getActivity(), FileConstants.YingJi,JSON.toJSONString(array));
            UserSPUtils.putUserString(getActivity(), FileConstants.HasReport,"true");
            setRV_advice_detail();
        }
    }

    public void showShanshiData(String msg) {
        ReceiveData receiveData = JSONObject.parseObject(msg, ReceiveData.class);
        if (!receiveData.getCode().equals("200")) {
            Activity.ErrorDialog(receiveData.getMessage());
        } else {
            List<DietHealthData> dietHealthDatas = JSONArray.parseArray(receiveData.getData(), DietHealthData.class);
            List<V2AdviceDetailData> shanshiData = new ArrayList<>();
            HealthCareData_shanshi.clear();
            shanshi.clear();
            for (int i = 0; i < dietHealthDatas.size(); i++) {
                HealthCareData AdDatas = new HealthCareData(dietHealthDatas.get(i).getId() + "",

                        dietHealthDatas.get(i).getDietName(),
                        "膳食养生",
                        dietHealthDatas.get(i).getDietImages(),
                        dietHealthDatas.get(i).getDietMaterial(),
                        dietHealthDatas.get(i).getDietMaking(),
                        dietHealthDatas.get(i).getDietEfficacy(),
                        dietHealthDatas.get(i).getDietTaboo());
                HealthCareData_shanshi.add(AdDatas);
                shanshi.add(dietHealthDatas.get(i).getId() + "");
                reportIDToHealthCareID.setShanshi(shanshi);


                V2AdviceDetailData V2Data=new V2AdviceDetailData();
                V2Data.setImageUrl(dietHealthDatas.get(i).getDietImages());
                V2Data.setYsName(dietHealthDatas.get(i).getDietName());
                V2Data.setId(dietHealthDatas.get(i).getId());
                V2Data.setCategoryName("饮食指导");
                V2Data.setRawMaterial(dietHealthDatas.get(i).getDietMaterial());
                V2Data.setPrinciple(dietHealthDatas.get(i).getDietMaking());
                V2Data.setEffect(dietHealthDatas.get(i).getDietEfficacy());
                V2Data.setTaboo(dietHealthDatas.get(i).getDietTaboo());
                shanshiData.add(V2Data);
            }

            JSONArray array= JSONArray.parseArray(JSON.toJSONString(shanshiData));
            UserSPUtils.putUserString(getActivity(), FileConstants.Yinshi_data,JSON.toJSONString(array));
            UserSPUtils.putUserString(getActivity(), FileConstants.HasReport,"true");
            setRV_advice_detail();
        }
    }


    public void showYaoyuData(String msg) {
        ReceiveData receiveData = JSONObject.parseObject(msg, ReceiveData.class);
        if (!receiveData.getCode().equals("200")) {
            Activity.ErrorDialog(receiveData.getMessage());
        } else {
            List<MedicatedBathData> medicatedBathDatas = JSONArray.parseArray(receiveData.getData(), MedicatedBathData.class);
            List<V2AdviceDetailData> zuyuData = new ArrayList<>();
            HealthCareData_yaoyu.clear();
            yaoyu.clear();
            for (int i = 0; i < medicatedBathDatas.size(); i++) {
                HealthCareData AdDatas = new HealthCareData(medicatedBathDatas.get(i).getId() + "",
                        medicatedBathDatas.get(i).getMedicineName(),
                        "药浴养生",
                        medicatedBathDatas.get(i).getMedicineImages(),
                        medicatedBathDatas.get(i).getMedicineMaterial(),
                        medicatedBathDatas.get(i).getMedicineUsage(),
                        medicatedBathDatas.get(i).getMedicineCure(),
                        medicatedBathDatas.get(i).getMedicineTaboo());
                HealthCareData_yaoyu.add(AdDatas);
                yaoyu.add(medicatedBathDatas.get(i).getId() + "");
                reportIDToHealthCareID.setYaoyu(yaoyu);


                V2AdviceDetailData V2Data=new V2AdviceDetailData();
                V2Data.setImageUrl(medicatedBathDatas.get(i).getMedicineImages());
                V2Data.setYsName(medicatedBathDatas.get(i).getMedicineName());
                V2Data.setId(medicatedBathDatas.get(i).getId());
                V2Data.setCategoryName("足浴指导");
                V2Data.setRawMaterial(medicatedBathDatas.get(i).getMedicineMaterial());
                V2Data.setEffect(medicatedBathDatas.get(i).getMedicineCure());
                V2Data.setPrinciple(medicatedBathDatas.get(i).getMedicineUsage());
                V2Data.setTaboo(medicatedBathDatas.get(i).getMedicineTaboo());
                zuyuData.add(V2Data);
            }
            JSONArray array= JSONArray.parseArray(JSON.toJSONString(zuyuData));
            UserSPUtils.putUserString(getActivity(), FileConstants.Zuyu_data,JSON.toJSONString(array));
            UserSPUtils.putUserString(getActivity(), FileConstants.HasReport,"true");
            setRV_advice_detail();
        }
    }


    public void showChayinData(String msg) {
        ReceiveData receiveData = JSONObject.parseObject(msg, ReceiveData.class);
        if (!receiveData.getCode().equals("200")) {
            Activity.ErrorDialog(receiveData.getMessage());
        } else {
            List<TeaHealthData> teaHealthDatas = JSONArray.parseArray(receiveData.getData(), TeaHealthData.class);
            List<V2AdviceDetailData> chayinData = new ArrayList<>();
            HealthCareData_chayin.clear();
            chayin.clear();
            for (int i = 0; i < teaHealthDatas.size(); i++) {
                HealthCareData AdDatas = new HealthCareData(teaHealthDatas.get(i).getId() + "",
                        teaHealthDatas.get(i).getTeaName(),
                        "茶饮养生",
                        teaHealthDatas.get(i).getTeaImages(),
                        teaHealthDatas.get(i).getTeaMaterial(), teaHealthDatas.get(i).getTeaMaking(),
                        teaHealthDatas.get(i).getTeaEfficacy(),
                        teaHealthDatas.get(i).getTeaTaboo());
                HealthCareData_chayin.add(AdDatas);
                chayin.add(teaHealthDatas.get(i).getId() + "");
                reportIDToHealthCareID.setChayin(chayin);

                V2AdviceDetailData V2Data=new V2AdviceDetailData();
                V2Data.setImageUrl(teaHealthDatas.get(i).getTeaImages());
                V2Data.setYsName(teaHealthDatas.get(i).getTeaName());
                V2Data.setId(teaHealthDatas.get(i).getId());
                V2Data.setCategoryName("饮食指导");
                V2Data.setRawMaterial(teaHealthDatas.get(i).getTeaMaterial());
                V2Data.setEffect(teaHealthDatas.get(i).getTeaEfficacy());
                V2Data.setPrinciple(teaHealthDatas.get(i).getTeaMaking());
                V2Data.setTaboo(teaHealthDatas.get(i).getTeaTaboo());
                chayinData.add(V2Data);
            }
            JSONArray array= JSONArray.parseArray(JSON.toJSONString(chayinData));
            UserSPUtils.putUserString(getActivity(), FileConstants.ChaYin,JSON.toJSONString(array));
            UserSPUtils.putUserString(getActivity(), FileConstants.HasReport,"true");
            setRV_advice_detail();
        }
    }


    public void showAijiuData(String msg) {
        ReceiveData receiveData = JSONObject.parseObject(msg, ReceiveData.class);
        if (!receiveData.getCode().equals("200")) {
            Activity.ErrorDialog(receiveData.getMessage());
        } else {
            List<MoxibustionData> moxibustionDatas = JSONArray.parseArray(receiveData.getData(), MoxibustionData.class);
            List<V2AdviceDetailData> liliaoData = new ArrayList<>();
            HealthCareData_aijiu.clear();
            aijiu.clear();
            for (int i = 0; i < moxibustionDatas.size(); i++) {
                HealthCareData AdDatas = new HealthCareData(moxibustionDatas.get(i).getId() + "",
                        moxibustionDatas.get(i).getMoxibustionName(),
                        "艾灸养生",
                        moxibustionDatas.get(i).getMoxibustionImages(),
                        moxibustionDatas.get(i).getMoxibustionDescription(),
                        moxibustionDatas.get(i).getMoxibustion(),
                        moxibustionDatas.get(i).getMoxibustionEfficacy(),
                        moxibustionDatas.get(i).getMoxibustionPosition());
                HealthCareData_aijiu.add(AdDatas);
                aijiu.add(moxibustionDatas.get(i).getId() + "");
                reportIDToHealthCareID.setAijiu(aijiu);

                V2AdviceDetailData V2Data=new V2AdviceDetailData();
                V2Data.setImageUrl(moxibustionDatas.get(i).getMoxibustionImages());
                V2Data.setId(moxibustionDatas.get(i).getId());
                V2Data.setCategoryName("理疗指导");
                V2Data.setYsName(moxibustionDatas.get(i).getMoxibustionName());
                V2Data.setPosition(moxibustionDatas.get(i).getMoxibustionPosition());
                V2Data.setEffect(moxibustionDatas.get(i).getMoxibustionEfficacy());
                V2Data.setPrinciple(moxibustionDatas.get(i).getMoxibustion());
                V2Data.setBeCareful(moxibustionDatas.get(i).getMoxibustionDescription());
                liliaoData.add(V2Data);
            }
            JSONArray array= JSONArray.parseArray(JSON.toJSONString(liliaoData));
            UserSPUtils.putUserString(getActivity(), FileConstants.Liliao_data,JSON.toJSONString(array));
            UserSPUtils.putUserString(getActivity(), FileConstants.HasReport,"true");
            setRV_advice_detail();
        }
    }


    private MyHandler myHandler = new MyHandler(getActivity());

    private class MyHandler extends Handler {
        private final WeakReference<Context> reference;
        private HealthReportActivity activity;

        public MyHandler(Context context) {
            reference = new WeakReference<>(context);
            activity = (HealthReportActivity) reference.get();
        }

        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 11://获取楔子养生的详细信息并跳转
                    showXieziHealthData(msg.obj.toString());
                    break;
                case 12://获取运动养生的详细信息并跳转
                    showYundongData(msg.obj.toString());
                    break;
                case 13://获取季节养生的详细信息并跳转
                    showJijieData(msg.obj.toString());
                    break;
                case 14://获取膳食养生的详细信息并跳转
                    showShanshiData(msg.obj.toString());
                    break;
                case 15://获取药浴养生的详细信息并跳转
                    showYaoyuData(msg.obj.toString());
                    break;
                case 16://获取茶饮养生的详细信息并跳转
                    showChayinData(msg.obj.toString());
                    break;
                case 17://获取艾灸养生的详细信息并跳转
                    showAijiuData(msg.obj.toString());
                    break;
                case 101:
                    if (activity.pDialog.isShowing()) {
                        activity.pDialog.dismiss();
                    }
                    break;
            }
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        myHandler.removeCallbacksAndMessages(null);
    }



}